<template>
  <div class="connect">
    <div class="connect_box">
      <el-form :inline="true"   :model="selectForm" class="demo-form-inline">
        <!-- <el-form-item :label="$t('Order_module.Destination_Country_Region')">
          <el-select v-model="value" :placeholder="$t('Order_module.Destination_Country_Region') ">
              <el-option
                v-for="item in selectForm.country"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
        </el-form-item> -->
        <el-form-item :label="$t('Order_module.Recipient_Xing_Name')">
          <!-- 收件人姓名 -->
           <el-input v-model="selectForm.consigneeName" :placeholder="$t('Order_module.Recipient_Xing_Name') "></el-input>
        </el-form-item>
        <el-form-item :label="$t('Order_module.PRINT_STATUS')">
          <!-- 打印状态 -->
          <el-select v-model="selectForm.printStatus" :placeholder="$t('Order_module.PRINT_STATUS') ">
              <el-option
                v-for="item in printStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item :label="$t('Order_module.creation_date')">
          <!-- 开始时间结束时间 -->
          <el-date-picker
                value-format="yyyy-MM-dd HH:mm:ss"
                v-model="selectForm.Time"
                type="datetimerange"
                @change="pickerOptions_star"
                range-separator="-"
                :start-placeholder="$t('Order_module.Select_Date')"
                :end-placeholder="$t('Order_module.Select_Date')">
              </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('Order_module.User')">
          <!-- 用户下拉 -->
          <el-select v-model="selectForm.customerId" :placeholder="$t('Order_module.User') ">
              <el-option v-for="item in userList" :key="item.id" :label="item.userName" :value="item.id">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item :label="$t('Order_module.Batch_number')">
          <!-- 批次号 -->
            <el-input v-model="selectForm.manifestNo" :placeholder="$t('Order_module.Batch_number') "></el-input>
        </el-form-item>
        <el-form-item :label="$t('Order_module.Order_No')">
          <!-- 订单号 -->
            <el-input v-model="selectForm.orderNumber" :placeholder="$t('Order_module.Order_No') "></el-input>
        </el-form-item>
        <el-form-item :label="$t('Order_module.Waybill_number')">
          <!-- 运单号 -->
            <el-input v-model="selectForm.logisticsNo" :placeholder="$t('Order_module.Waybill_number') "></el-input>
        </el-form-item>
        <!-- 筛选 -->
        <el-button type="primary" @click="searchSubmit">{{$t('public.query')}}</el-button>
        <!-- 重置 -->
        <el-button type="primary" @click="resetting">{{$t('public.resetting')}}</el-button>
      </el-form>
      <div class="btns_ayyay">
         <!-- <el-button>{{$t('Order_module.export_list')}}</el-button> -->
         <!-- 条件导出 -->
         <!-- <el-button @click="Conditional_export">{{$t('public.Conditional_export')}}</el-button> -->
         <!-- 选择导出 -->
         <el-button :loading="doPrintLoading"  @click="doPrint">{{$t('Order_module.Print_face_sheet')}}</el-button>
         <el-button :loading="doPreviewLoading" @click="doPreview">{{$t('public.preview')}}</el-button>
         <el-button @click="sleect_export">{{$t('public.select_export')}}</el-button>
         <!-- 拉取单号 -->
         <el-button :loading="pullOrderNumLoading" @click="pullOrderNum()">{{$t('public.Pull_order_number')}}</el-button>
         <!-- 驱动下载 -->
         <el-button :loading="DownLoadFileLoading" @click="DownLoadFile()">{{$t('Order_module.Driver_Download')}}</el-button>
      </div>
        <!-- <el-table :data="tableData" border stripe style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column align="center" type="selection" width="55"> </el-table-column>
          <el-table-column align="center" prop="Order_No" :label="$t('Order_module.Order_No')"  min-width="180"> </el-table-column>
          <el-table-column align="center" prop="Waybill_number" :label="$t('Order_module.Waybill_number')"  min-width="180"> </el-table-column>
          <el-table-column align="center" prop="product_name" :label="$t('public.product_name')"  min-width="180"> </el-table-column>
          <el-table-column align="center" prop="Creation_time" :label="$t('public.Creation_time')"  min-width="180"> </el-table-column>
          <el-table-column align="center" prop="Batch_number" :label="$t('Order_module.Batch_number')"  min-width="180"> </el-table-column>
        </el-table> -->
        <!-- <el-checkbox-group v-model="groupList" @change="groupChange"> -->
          <el-table  @selection-change="handleSelectionChange" border  tooltip-effect="dark" :data="tableData"
            style="width: 100%">
             <!-- 多选 -->
             <el-table-column align="center" type="selection" width="55"> </el-table-column>
             <!-- <el-table-column align="center" prop="manifestNo" :label="$t('Order_module.Batch_number')"  width="50">
               <template slot="header" slot-scope="scope">
                     <el-checkbox  @change="handleCheckAllChange" label="all" >{{''}}</el-checkbox>
               </template>
               <template slot-scope="{row}">
                     <el-checkbox :disabled="row.logisticsNo?true:false" :label="row.id" >{{''}}</el-checkbox>
               </template>
             </el-table-column> -->
             <!-- 批次号 -->
             <el-table-column align="center" prop="manifestNo" :label="$t('Order_module.Batch_number')"  min-width="180"></el-table-column>
             <!-- 订单号 -->
            <el-table-column align="center" prop="orderNumber" :label="$t('Order_module.Order_No')"  min-width="180"></el-table-column>
            <!-- 快递号 -->
            <el-table-column align="center" prop="logisticsNo" :label="$t('public.logisticsNo')"  min-width="180">
              <template slot-scope="{row}">
                {{row.logisticsNo?row.logisticsNo:'-'}}
              </template>
            </el-table-column>
            <!-- 订单状态 -->
            <el-table-column align="center" prop="orderNumber" :label="$t('public.order_status')"  min-width="120">
              <template slot-scope="{row}">
                <span v-if="row.orderStatus==0">{{$t('public.placed_an_orde')}}</span>
                <span v-if="row.orderStatus==1">{{$t('public.Ordered')}}</span>
                <span v-if="row.orderStatus==2">{{$t('public.Pull_failure')}}</span>
                <span v-if="row.orderStatus==3">{{$t('public.Recycling_Center')}}</span>
                <span v-if="row.orderStatus==4">{{$t('public.Dead')}}</span>
                <span v-if="row.orderStatus==5">{{$t('public.Vendor_confirmation')}}</span>
                <span v-if="row.orderStatus==6">{{$t('public.Service_provider_declaration')}}</span>
                <span v-if="row.orderStatus==7">{{$t('public.Receipt_for_Application')}}</span>
                <span v-if="row.orderStatus==8">{{$t('public.banding_machine_residual')}}</span>
                <span v-if="row.orderStatus==9">{{$t('public.Under_purchase')}}</span>
                <span v-if="row.orderStatus==10">{{$t('public.Received')}}</span>
              </template>
            </el-table-column>
            <!-- 打印状态 -->
            <el-table-column align="center" prop="orderNumber" :label="$t('public.Print_mode')"  min-width="120">
              <template slot-scope="{row}">
                <span v-if="row.printStatus==0">{{$t('public.No_Print_head')}}</span>
                <span v-if="row.printStatus==1">{{$t('public.printed')}}</span>
              </template>
            </el-table-column>
            <!-- 所属用户 -->
            <el-table-column align="center" prop="userName" :label="$t('Order_module.User')"  min-width="120"></el-table-column>
            <!-- 代理名称 -->
            <!-- <el-table-column align="center" prop="agentName" :label="$t('public.agentName')"  min-width="120"></el-table-column> -->
            <!-- 创建时间 -->
            <el-table-column align="center" prop="createTime" :label="$t('Order_module.creation_date')"  min-width="200"></el-table-column>
            <!-- 客户重量 -->
            <el-table-column align="center" prop="userWeight" :label="$t('public.Declared_weight')"  min-width="120"></el-table-column>
            <!-- 京东重量 -->
            <el-table-column align="center" prop="jdWeight" :label="$t('public.JD_Weight')"  min-width="120">
              <template slot-scope="{row}">
                {{row.jdWeight?row.jdWeight:'-'}}
              </template>
            </el-table-column>
            <!-- 包裹数量 -->
            <el-table-column align="center" prop="packageNum" :label="$t('Order_module.Number_of_packages')"  min-width="120"></el-table-column>
            <!-- 发件人 -->
            <el-table-column align="center" prop="senderName" :label="$t('public.Sender_name')"  min-width="120"></el-table-column>
            <!-- 收件人 -->
            <el-table-column align="center" prop="consigneeName" :label="$t('Order_module.Recipient_Xing_Name')"  min-width="120"></el-table-column>
          </el-table>
        <!-- </el-checkbox-group> -->
        <div style="margin-top: 20px;"></div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[10, 50, 200, 400]"
          :page-size="limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
    </div>
  </div>
</template>

<script>
  import {
      order_lottingList,
      order_searchUser,
      order_orderExport,
      expressWaybill_info,
      manifest_billing,
      order_getOrderByIds,
      notifyPrintResult,
      caiNiaoPrint
    } from '@/api/wqzApi'
  export default {
    components: {},
    data() {
      return {
        pullOrderNumLoading:false,
        DownLoadFileLoading:false,
        doPrintLoading:false,
        doPreviewLoading:false,
        isCheckdAll:false,//是否全选
        allLength:0,//全选时候的可选长度
        indeterminate:false,
        groupList:[],
        value:null,
        options:[
          {value:1 , label:'选项1'},
          {value:2 , label:'选项1'},
          {value:3 , label:'选项1'},
          {value:4 , label:'选项1'},
        ],
        total:0,
        limit:10,
        page:1,
        selectForm:{
          consigneeName:'',//收件人姓名
          customerId:'',//所属用户id
          manifestNo:'',//批次号
          orderNumber:'' , //订单号
          logisticsNo:'',//运单号
          printStatus:'' , //打印状态(0.未打印1.已打印)
          startTime:'' , //开始日期
          endTime:'' , //结束日期
          Time:[],//开始日期和结束日期
        },
        printStatusList:[ //打印状态
          {value: 1,label: '已打印'},
          {value: 0,label: '未打印'}
        ],
        userList : [], // 所属用户列表
        tableData:[],
        chooseItem:[],
        waybillTemplateURL:process.env.VUE_APP_BASE_API + '/printer/middle',
        printTaskId:0,
        socket:null,
        printers:null,
        defaultPrinter:null,
        waybillNO:'000000000000',
        print_logisticsNos:[], //打印面单信息
        formInline:{
          time:'',
          user:'',

        }
      }
    },

    created() {
    },
    mounted() {
      this.getList()
      this.getUserList()
      this.doConnect()
    },
    destroyed() {

    },
    methods: {
      DownLoadFile(){
        // 驱动下载
        this.DownLoadFileLoading = true
        this.$export_down2(caiNiaoPrint() , [] , 'CNPrintClient' , '.exe' ).then(res=>{
          this.DownLoadFileLoading = false
        }).catch(err=>{
        })
      },
      groupChange(e){
        var arr = []
        this.groupList = e
        if(this.groupList.length==this.tableData.length){
          // 如果多选组的长度和表格长度一致 需要判断多选组的第一项是不是全选按钮 不是就表示为全选添加全选按钮选中 是就没有全选需要删除全选的状态
            if(this.groupList[0]=='all'){
              // 删除全选状态
                this.groupList.shift()
            }else{
              // 增加全选状态
              this.groupList.unshift('all')
            }
        }
        // 多选按钮组长度加1和列表长度一致表示已经全选了
        var isAll = this.tableData.length+1 == this.groupList.length
        e.forEach((item,index)=>{
          if(isAll || this.isCheckdAll ){
            //点击全选按钮的 需要判断符不符合全选条件 不符合就不是全选
            if(this.groupList[0]!='all'){
              // 多选组 第一项不是全选 增加第一项为全选
              this.groupList.unshift('all')
            }
            // 多选租的长度不等于全选可选总长度 为 非全选
            if(this.groupList.length != this.allLength){
              if(this.groupList[0]=='all' && this.isCheckdAll){
                // 去除全选按钮选中状态
                if(this.groupList[0]=='all' && this.isCheckdAll){
                  // 去除全选按钮选中状态
                  this.groupList.shift()
                }
              }
            }
          }else{
            // 不是全选去掉全选项 this.isCheckdAll是因为有的不能选 全选后不能选的不能被选中 故 长度和 isCheckdAll 只满足一个就是全选
            if(this.groupList[0]=='all' && this.isCheckdAll){
              if(this.groupList[0]=='all' && this.isCheckdAll){
                // 去除全选按钮选中状态
                this.groupList.shift()
              }
            }
            if(this.groupList.length == this.allLength){
              if(this.groupList[0] !='all' && this.isCheckdAll==false){
                // 去除全选按钮选中状态
                this.groupList.unshift('all')
              }else{
                if(this.groupList[0]=='all' && this.isCheckdAll){
                  // 去除全选按钮选中状态

                  this.groupList.shift()
                }

              }
            }
          }
        })
        this.groupList.forEach((item,index)=>{
          if(item !== 'all'){
            arr.push({id:item})
          }
        })
        this.chooseItem = arr
      },
      handleCheckAllChange(e){
        this.isCheckdAll = e
        if(e){
          //全选
          this.groupList = []
          this.groupList.push('all')
          this.tableData.forEach((item,index)=>{
            if(item.logisticsNo=='' || item.logisticsNo==null){
              this.groupList.push(item.id)
            }
          })
          this.allLength = this.groupList.length

        }else{
          // 全不选
          this.groupList = []
        }
      },
      pullOrderNum(){
        var ids = []
        this.pullOrderNumLoading = true
        if(this.chooseItem.length<=0){
          this.$message({
            type:'warning',
            message:this.$t('public.Please_select_id')
          })
          this.pullOrderNumLoading = false
          return
        }
        this.chooseItem.forEach((item,index)=>{
          if(item.id == 'all'){

          }else{
            ids.push(item.id)
          }
        })
        order_getOrderByIds(ids).then(res=>{
          manifest_billing(res.list).then(req=>{
            this.$message({
              type:'success',
              message:req.msg
            })
            this.pullOrderNumLoading = false
            this.getList()
          }).catch(err=>{
            this.pullOrderNumLoading = false
          })
        })
      },
      doConnect() {
        var that = this
          this.socket = new WebSocket('ws://127.0.0.1:13528');
          var result = "打印成功";
          var tmptaskID = "0";
          var that = this
          // 打开Socket
          that.socket.onopen = function (event) {
              // 监听消息
              that.socket.onmessage = function (event) {

                  var data = JSON.parse(event.data);
                  that.printers = data.printers;
                  that.defaultPrinter = data.defaultPrinter;
                  if (data.cmd == 'notifyPrintResult') {
                      var result = "打印成功";
                      if (data.taskID != tmptaskID) {
                          for (var i = 0; i < data.printStatus.length; i++) {
                              if (data.printStatus[i].status == 'failed') {
                                  result = "打印失败";
                                  break;
                              } else if (data.printStatus[i].status == 'canceled') {
                                  result = "取消打印任务";
                                  break;
                              }
                          }
                          tmptaskID = data.taskID;
                      }
                  } else if (data.cmd == "print") {
                      if (data.previewURL){
                        notifyPrintResult(that.print_logisticsNos).then(res=>{
                          window.open(data.previewURL);
                          that.getList()
                        })
                      }


                  }

              };
              // 监听Socket的关闭
              that.socket.onclose = function (event) {
                  console.log("打印机失去联系，请刷新网页重新连接");
                  // this.$message({

                  // })
              };
          };
          that.socket.onerror = function (event) {
              console.log("打印机出现问题,请联系客服");
          }
      },

      doPreview() {
        this.doPreviewLoading = true
      var dataArr = []
      if(this.chooseItem.length<=0){
        this.$message({type:'warning' , message:this.$t('public.Please_select_id')})
        this.doPreviewLoading = false
        return
      }

      this.chooseItem.forEach((item,index)=>{
        dataArr.push(item.logisticsNo)
      })

      // var formData = new FormData();
      // formData.logisticsNo = dataArr
      expressWaybill_info(dataArr).then(res=>{
        var arr = []
        if(res.list.length<=0){
          this.doPreviewLoading = false
          this.$message({
            type:'warning',
            message:this.$t('public.No_printing_information_is_available')
          })
          return
        }
        res.list.forEach((item,index)=>{
             var dataArrs ={
               documentID:this.waybillNO,
               contents:[
                 {
                       templateURL: this.waybillTemplateURL,
                       signature: "MD:kw4V6Gtj/7ZasLyotby+HA==",
                       data:item
                 }
               ]
             }
            arr.push(dataArrs)
            this.print_logisticsNos = []
            this.print_logisticsNos.push(item.logisticsNo)
        })
        // console.log(this.chooseItem , arr ,'选中结果' )
        // this.doPreviewLoading = false
        // return
        this.doPreviewLoading = false
        var printData = this.getPrintData(arr);
        printData.task.preview = true;
        this.socket.send(JSON.stringify(printData));
      }).catch(err=>{
        this.doPreviewLoading = false
      })


      },
      //打印电子面单
       doPrint() {
          var dataArr = []
          this.doPrintLoading = true
          if(this.chooseItem.length<=0){
            this.$message({type:'warning' , message:this.$t('public.Please_select_id')})
            this.doPrintLoading =  false
            return
          }
          this.chooseItem.forEach((item,index)=>{
            dataArr.push(item.logisticsNo)
          })
          // var formData = new FormData();
          // formData.logisticsNo = dataArr
          expressWaybill_info(dataArr).then(res=>{
            var arr = []
            if(res.list.length<=0){
              this.$message({
                type:'warning',
                message:this.$t('public.No_printing_information_is_available')
              })
              this.doPrintLoading = false
              return
            }
            res.list.forEach((item,index)=>{
                 var dataArrs ={
                   documentID:this.waybillNO,
                   contents:[
                     {
                           templateURL: this.waybillTemplateURL,
                           signature: "MD:kw4V6Gtj/7ZasLyotby+HA==",
                           data:item
                     }
                   ]
                 }
                arr.push(dataArrs)
                this.print_logisticsNos = []
                this.print_logisticsNos.push(item.logisticsNo)
            })
            this.doPrintLoading =  false
            var printData = this.getPrintData(arr);
            this.socket.send(JSON.stringify(printData));
          }).catch(err=>{
            this.doPrintLoading =  false
          })
      },
      getPrintData(arr) {
        if(arr.length<=0){
            this.$message({
              type:'warning',
              message:this.$t('public.No_printing_information_is_available')
            })
            return
          }
          this.waybillNO = "123456789123";
          this.printTaskId = parseInt(1000 * Math.random());
          var request = {
              cmd: "print",
              requestID: "12345678901234567890",
              version: "1.0",
              task: {
                   taskID: '' + this.printTaskId,
                   preview: false,
                   printer: this.defaultPrinter,
                   notifyMode: "allInOne",
                   previewType:'pdf',
                   documents: arr
              }
          };
          return request;
      },
        getUUID(len, radix) {
            var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
            var uuid = [], i;
            radix = radix || chars.length;
            if (len) {
                for (var i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
            } else {
                var r;
                uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                uuid[14] = '4';
                for (var i = 0; i < 36; i++) {
                    if (!uuid[i]) {
                        r = 0 | Math.random() * 16;
                        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                    }
                }
            }
            return uuid.join('');
        },








      sleect_export(){
        // 选择导出
        var ids = []
         this.chooseItem.forEach((item,index)=>{
          ids.push(item.manifestNo)
        })
        if(ids.length<=0){
          this.$message({
            type:'warning',
            message:this.$t('public.Please_select_id'),
          })
          return
        }
        this.$export_down(order_orderExport() , ids , this.$t('route.Waybill_Query'))
      },
      // 重置
      resetting(){
        this.selectForm = {
          consigneeName:null,//收件人姓名
          customerId:null,//所属用户id
          manifestNo:null,//批次号
          orderNumber:null , //订单号
          logisticsNo:null,//运单号
          printStatus:null , //打印状态(0.未打印1.已打印)
          startTime:null , //开始日期
          endTime:null , //结束日期
          Time:[],//开始日期和结束日期
        },
        this.getList()
      },
      pickerOptions_star(e){
        // 选择订单穿件时间
        if(e==null){
          this.selectForm.Time = e
          this.selectForm.startTime = ''
          this.selectForm.endTime = ''
        }else{
          this.selectForm.Time = e
          this.selectForm.startTime = e[0]
          this.selectForm.endTime = e[1]
        }
      },
      searchSubmit(){
        this.page = 1
        this.getList()
      },
      getUserList(){
        // 筛选条件的userlist
        order_searchUser({}).then(res=>{
          this.userList = res.users
        })
      },
      getList(){
        var data = JSON.parse(JSON.stringify(this.selectForm))
        delete data.Time
        data.page = this.page
        data.limit = this.limit
        order_lottingList(data).then(res=>{
          this.tableData = res.page.list
          this.allLength = 0
          this.tableData.forEach((item , index)=>{
            // item.logisticsNo = ''
            if(item.logisticsNo=='' || item.logisticsNo==null){
              this.allLength+=1
            }
          })
          this.total = res.page.totalCount
        })
      },
      handleSelectionChange(e){
        this.chooseItem = e
      },
      handleSizeChange(e){
        this.limit = e
        this.getList()
      },
      handleCurrentChange(e){
        this.page = e
        this.getList()
      }
    }
  }
</script>

<style scoped>
  @import url('Waybill_Query.css');
</style>
